import { useMemo } from 'react';
import { View, Text } from '@tarojs/components';
import './index.<%= css %>';

interface ICommonProgress {
  wrapperStyle?: any;
  outerStyle?: any;
  innerStyle?: any;
  value: number;
  showTxt?: boolean;
  endBgcolor?: string;
}

const CommonProgress = (props: ICommonProgress) => {
  const { wrapperStyle, outerStyle, innerStyle = {}, value = 0, showTxt = false, endBgcolor } = props;

  const receiveValue = useMemo(() => {
    if (typeof value !== 'number' || value < 0) {
      return '0%';
    }
    return `${value > 100 ? 100 : value}%`;
  }, [value]);

  const progressStyle = useMemo(() => {
    const commonStyle = { ...innerStyle, width: receiveValue };
    if (value >= 100 && endBgcolor) {
      return { ...commonStyle, backgroundColor: endBgcolor };
    }
    return commonStyle;
  }, [value, receiveValue]);

  return (
    <View className="common-pregress-wrapper" style={wrapperStyle}>
      <View className="outer" style={{ ...outerStyle }}>
        <View className="inner" style={progressStyle} />
      </View>
      {!showTxt && <Text className="inner-txt">{`${value < 0 ? 0 : value}%`}</Text>}
    </View>
  );
};

export default CommonProgress;
